//
//  OAEmailViewController.m
//  LongOA
//
//  Created by XuJiuming on 15/9/16.
//  Copyright (c) 2015年 梁文朗. All rights reserved.
//

#import "OAEmailViewController.h"
#import "HYSegmentedControl.h"
#import "OANewEmailViewController.h"
#import "GetEmailListRequest.h"
#import "GetEmailListRespones.h"
#import "MJRefresh.h"
#import "OAReceiveDetailViewController.h"
#import "OASendDetailViewController.h"
#import "OATempMail.h"
#import "OANewEmailViewController.h"

@interface OAEmailViewController ()<HYSegmentedControlDelegate,UITableViewDataSource,UITableViewDelegate>
{
    NSArray* arrList;
    UITableView* _tableView;
    int isegment;
    int msgid;  //最小
    int msgidm; //最大
    
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    
    int iRtnCount;      //返回记录数量，判断是否足10，加 没有更多数据显示
}
@property (strong, nonatomic) HYSegmentedControl *segmentedControl;
@end

@implementation OAEmailViewController

- (void)leftBarClicked:(id)sender {
    [self dismissViewControllerAnimated:NO completion:nil];
}
- (void)viewWillAppear:(BOOL)animated  {
    if (arrList.count>0) {
        arrList=nil;
    }
  
    [self getEmailList:0 withgo:NO withlast:0];
}
- (void)rightBarClicked:(id)sender {
    OANewEmailViewController* vc=[[OANewEmailViewController alloc] init];
    //[self.navigationController pushViewController:vc animated:NO];
    [self presentViewController:vc animated:NO completion:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    isegment=0;
    NSString* strsub=[[NSUserDefaults standardUserDefaults] objectForKey:@"accname"];
    strsub=[NSString stringWithFormat:@"[%@]",strsub];
    [self createNavWithTitleSub:@"内部邮件" subtitle:strsub createMenuItem:^UIView *(int nIndex)
     {
         float btnwidth=40.0f;
         float btnheight=40.0f;
         if (nIndex ==0)
         {
             UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
             [btn setFrame:CGRectMake(10.0f, 20.0f+(self.navView.height-20 - 40)/2, btnwidth, btnheight)];
             [btn setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
             [btn addTarget:self action:@selector(leftBarClicked:) forControlEvents:UIControlEventTouchUpInside];
             btn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
             return btn;
         }
         
         if (nIndex ==2)
         {
             UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
             [btn setFrame:CGRectMake(self.navView.width - btnwidth - 10.0f, 20.0f+(self.navView.height-20 - 40)/2, btnwidth, btnheight)];
             [btn setImage:[UIImage imageNamed:@"ic_edit"] forState:UIControlStateNormal];
             [btn addTarget:self action:@selector(rightBarClicked:) forControlEvents:UIControlEventTouchUpInside];
             
             return btn;
         }

         return nil;
     }];

    self.segmentedControl = [[HYSegmentedControl alloc] initWithOriginY:self.navView.bottom Titles:@[@"收件箱", @"发件箱", @"草稿箱"] delegate:self];
    [self.view addSubview:_segmentedControl];
    //[[HYSegmentedControl sharedInstance] changeSegmentedControlWithIndex:1];
    
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0.0, self.segmentedControl.bottom, SCREEN_WIDTH, SCREEN_HEIGHT-self.segmentedControl.bottom) style:UITableViewStylePlain];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.backgroundColor=[UIColor clearColor];
    _tableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    [self.view addSubview:_tableView];
    [self setExtraCellLineHidden:_tableView];
    
    [self addHeaderAndFooter];
    
    [self getEmailList:0 withgo:NO withlast:0];
    
    //刷新草稿箱
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshDraft:) name:@"refreshDraft" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshSend) name:@"refreshSend" object:nil];
}
- (void)refreshSend {
    //-[__NSDictionaryM savetime1]: unrecognized selector sent to instance 0x7fca3dc5bb80
    //三个分页的结构不同，造成 savetime1报错，加此句控制报错
    isegment=1;
}
- (void)refreshDraft:(NSNotification*)notif {
    NSString* temp=notif.object;
    if(isegment==2 && [temp isEqualToString:@"Draft"]) {
        arrList=[OATempMail searchWithWhere:nil];
    
        [_tableView reloadData];
    }
}
- (void)addHeaderAndFooter
{
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = _tableView;
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        if (isegment==0) {
            [self getEmailList:0 withgo:YES withlast:msgidm];
        } else if (isegment==1) {
            [self getEmailList:1 withgo:YES withlast:msgidm];
        } else if (isegment==2) {
            arrList=[OATempMail searchWithWhere:nil];
            
            [_tableView reloadData];
        }
        [self endRefreshing];
    };
    _header = header;
    
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = _tableView;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        if (isegment==0) {
            [self getEmailList:0 withgo:NO withlast:msgid];
        } else if (isegment==1) {
            [self getEmailList:1 withgo:NO withlast:msgid];
        } else if (isegment==2) {
            arrList=[OATempMail searchWithWhere:nil];
            
            [_tableView reloadData];
        }
        [self endRefreshing];
    };
    _footer = footer;
}
-(void)endRefreshing{
    [_header endRefreshing];
    [_footer endRefreshing];
}

-(void)setExtraCellLineHidden: (UITableView *)tableView {
    UIView *view =[ [UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
    [tableView setTableHeaderView:view];
}
//dataBase/OAIpdataBase.m有初始化信息
/*
token	string	是		用户身份标识
type	int	是		1-我的发件，0-我的收件
ifGoingUp	bool	是		是否向上取
lastId	int	是		向上最大ID(顺序) 或向下最小ID 当为0时获取最大的10条记录(倒序)
*/
//收
- (void)getEmailList:(int)itag withgo:(BOOL)bgoing withlast:(int)lastid {
    if (iRtnCount==1 && [arrList count]<10) {
        return;
    }
    NSString* token=[[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    int setid=[[[NSUserDefaults standardUserDefaults] objectForKey:@"setid"] intValue];

    GetEmailListRequest* request = [[GetEmailListRequest alloc] init];
    request.token = token;
    request.type = itag;
    request.ifGoingUp = bgoing;
    request.lastId = lastid;
    id<ILJClient> clinet = [[OAIpdataBase shareInstance] getPool:setid];
    [clinet Doexecute:request
             RspClass:[GetEmailListRespones class]
               andMsg:@"获取信息..."
              andView:self.view
globalTimelinePostsWithBlock:^(id rsp) {
    GetEmailListRespones* rslt = rsp;

    if (rslt.ErrMsg) {
        NSLog(@"%@",rslt.ErrMsg);
    }
    else{
        if (arrList.count>0 && lastid!=0) {
            NSArray *myarray= rslt.list;
            int ii=(int)[myarray count];
            
            if (ii>0) {
                NSMutableArray *array=[[NSMutableArray alloc]init];
                [array addObjectsFromArray:arrList];
                [array addObjectsFromArray:myarray];
                
                arrList=array;
            }
        } else {
            arrList=rslt.list;
        }
        
        //NSLog(@"%@--%li",arrList,(unsigned long)[arrList count]);
        if ([rslt.list count]<10) {
            iRtnCount=1;
        }
        if ([arrList count]>0) {
            NSDictionary* dict=[arrList objectAtIndex:0];
            msgidm=[[dict objectForKey:@"msgid"] intValue];
            dict=[arrList objectAtIndex:[arrList count]-1];
            msgid=[[dict objectForKey:@"msgid"] intValue];
        }
        //NSLog(@"%@--%i--%i--%i",arrList,msgidm,msgid,lastid);
        
        [_tableView reloadData];
    }
}];
}
//发
- (void)getEmailList1:(int)itag withgo:(BOOL)bgoing withlast:(int)lastid {
    if (iRtnCount==1 && [arrList count]<10) {
        return;
    }
    
    NSString* token=[[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    int setid=[[[NSUserDefaults standardUserDefaults] objectForKey:@"setid"] intValue];
    
    GetEmailListRequest* request = [[GetEmailListRequest alloc] init];
    request.token = token;
    request.type = itag;
    request.ifGoingUp = bgoing;
    request.lastId = lastid;
    id<ILJClient> clinet = [[OAIpdataBase shareInstance] getPool:setid];
    [clinet Doexecute:request
             RspClass:[GetEmailListRespones class]
               andMsg:@"获取信息..."
              andView:self.view
globalTimelinePostsWithBlock:^(id rsp) {
    GetEmailListRespones* rslt = rsp;
    
    if (rslt.ErrMsg) {
        NSLog(@"%@",rslt.ErrMsg);
    }
    else{
//        if (arrList.count>0 && lastid!=0) {
//            NSArray *myarray= rslt.list;
//            int ii=(int)[myarray count];
//            
//            if (ii>0) {
//                NSMutableArray *array=[[NSMutableArray alloc]init];
//                [array addObjectsFromArray:arrList];
//                [array addObjectsFromArray:myarray];
//                
//                arrList=array;
//            }
//        } else {
            arrList=rslt.list;
//        }
        
        if ([rslt.list count]<10) {
            iRtnCount=1;
        }
        if ([arrList count]>0) {
            NSDictionary* dict=[arrList objectAtIndex:0];
            msgidm=[[dict objectForKey:@"msgid"] intValue];
            dict=[arrList objectAtIndex:[arrList count]-1];
            msgid=[[dict objectForKey:@"msgid"] intValue];
        }
        
        [_tableView reloadData];
    }
}];
}
#pragma mark HYSegmentedControl delegate
- (void)hySegmentedControlSelectAtIndex:(NSInteger)index
{
    switch (index) {
        case 0:
        {
            iRtnCount=0;
            isegment=0;
            if (arrList.count>0) {
                arrList=nil;
            }
           [self getEmailList:0 withgo:NO withlast:0];
        }
            break;
        case 1:
        {
            iRtnCount=0;
            isegment=1;
            if (arrList.count>0) {
                arrList=nil;
            }
            [self getEmailList1:1 withgo:NO withlast:0];
        }
            break;
        case 2:
        {
            iRtnCount=0;
            isegment=2;
            arrList=[OATempMail searchWithWhere:nil];
            
            [_tableView reloadData];
        }
            break;
        default:
            break;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark TableView delegate
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    //8.0的分割线额外设置
    if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 8.0) {
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:UIEdgeInsetsZero];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:UIEdgeInsetsZero];
        }
        
        if([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)])
            [cell setPreservesSuperviewLayoutMargins:NO];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (iRtnCount==1)
        return [arrList count] + 1;
     else
         return [arrList count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44.0;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"newCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

        cell.backgroundColor=[UIColor clearColor];
        cell.contentView.backgroundColor=[UIColor clearColor];
        
        float mleft=5.0;
        UILabel* lab2=[[UILabel alloc] initWithFrame:CGRectMake(mleft, 0.0, 120.0, 22.0)];
        lab2.backgroundColor=[UIColor clearColor];
        lab2.tag=11;
        lab2.textColor=[UIColor darkGrayColor];
        lab2.font=[UIFont systemFontOfSize:13.0f];
        [cell.contentView addSubview:lab2];
        
        UILabel* lab1=[[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-152.0, 0.0, 150.0, 22.0)];
        lab1.backgroundColor=[UIColor clearColor];
        lab1.tag=12;
        lab1.textColor=[UIColor darkGrayColor];
        lab1.font=[UIFont systemFontOfSize:11.0f];
        [cell.contentView addSubview:lab1];
        UIImageView* img=[[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-152.0-21.0*2/3-2.0, (22.0-21.0*2/3)/2, 21.0*2/3, 18.0*2/3)];
        img.image=[UIImage imageNamed:@"icon_status_attach"];
        img.tag=101;
        [cell.contentView addSubview:img];
        
        UILabel* lab3=[[UILabel alloc] initWithFrame:CGRectMake(mleft, lab2.bottom, 150.0, 20.0)];
        lab3.backgroundColor=[UIColor clearColor];
        lab3.tag=13;
        lab3.textColor=[UIColor darkGrayColor];
        lab3.font=[UIFont systemFontOfSize:11.0f];
        [cell.contentView addSubview:lab3];
        
        UILabel* lab4=[[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-185.0, lab2.bottom, 180.0, 20.0)];
        lab4.backgroundColor=[UIColor clearColor];
        lab4.tag=14;
        lab4.textColor=[UIColor darkGrayColor];
        lab4.font=[UIFont systemFontOfSize:11.0f];
        lab4.textAlignment=NSTextAlignmentRight;
        [cell.contentView addSubview:lab4];
        
//        UIView* vi=[[UIView alloc] initWithFrame:CGRectMake(15.0, 49.5, SCREEN_WIDTH-15.0, 0.5)];
//        vi.backgroundColor=[UIColor groupTableViewBackgroundColor];
//        [cell.contentView addSubview:vi];
        
        UILabel* lab22=[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0, SCREEN_WIDTH, 44.0)];
        lab22.backgroundColor=[UIColor clearColor];
        lab22.tag=22;
        lab22.text=@"没有更多数据";
        lab22.textColor=[UIColor darkGrayColor];
        lab22.font=[UIFont systemFontOfSize:12.0f];
        lab22.textAlignment=NSTextAlignmentCenter;
        [cell.contentView addSubview:lab22];
    }
    //没有更多数据
    UILabel* lab1=(UILabel*)[cell viewWithTag:11];
    UILabel* lab2=(UILabel*)[cell viewWithTag:12];
    UILabel* lab13=(UILabel*)[cell viewWithTag:13];
    UILabel* lab14=(UILabel*)[cell viewWithTag:14];
    UIImageView* imgview=(UIImageView*)[cell viewWithTag:101];
    UILabel* lab22=(UILabel*)[cell viewWithTag:22];
    if (indexPath.row==[arrList count]) {
        lab22.hidden=NO;
//        if (iRtnCount==1 && indexPath.row==[arrList count]-1) {
//            lab22.hidden=NO;
//        } else {
//            lab22.hidden=YES;
//        }
        lab1.hidden=YES;
        lab2.hidden=YES;
        lab13.hidden=YES;
        lab14.hidden=YES;
        imgview.hidden=YES;
        return cell;
    } else {
        lab22.hidden=YES;
        
        lab1.hidden=NO;
        lab2.hidden=NO;
        lab13.hidden=NO;
        lab14.hidden=NO;
        imgview.hidden=NO;
    }
    
    
//    UILabel* lab1=(UILabel*)[cell viewWithTag:11];
//    UILabel* lab2=(UILabel*)[cell viewWithTag:12];
//    UILabel* lab13=(UILabel*)[cell viewWithTag:13];
//    UILabel* lab14=(UILabel*)[cell viewWithTag:14];
//    UIImageView* imgview=(UIImageView*)[cell viewWithTag:101];
    
    if (isegment==2) {
        //NSLog(@"savetime1=====");
        //draft mail
        OATempMail* tempMail=[arrList objectAtIndex:indexPath.row];
        lab1.text=tempMail.title;
        lab2.text=[NSString stringWithFormat:@"[待发送]%@",tempMail.savetime1];
        lab13.text=tempMail.content;
        NSString* strTag=tempMail.atttag;
        if ([strTag isEqualToString:@"0"]) {
            imgview.hidden=YES;
        } else {
            imgview.hidden=NO;
        }
        lab14.text=tempMail.receiver;
        
        return cell;
    }
    
    NSDictionary* dict=[arrList objectAtIndex:indexPath.row];
    //NSLog(@"===%@",dict);
    /*
    if (indexPath.row==0) {
        msgid=[[dict objectForKey:@"msgid"] intValue];
        //NSLog(@"--%@",dict);
    }
    */
    lab1.text=[dict objectForKey:@"title"];
    
    int itag=[[dict objectForKey:@"dealFlag"] intValue];
    NSString* dealFlag=@"[待确认]";
    if (itag==1) {
        dealFlag=@"[已确认]";
    } else {
        lab1.textColor=[UIColor darkTextColor];
    }
    int iReadflag=[[dict objectForKey:@"readflag"] intValue];
    if (iReadflag==0) {
        lab1.textColor=[UIColor darkTextColor];
    }
    
    
    int ii=[[dict objectForKey:@"hasAttach"] intValue];
    
    if (ii==0)
        imgview.hidden=YES;
    else
        imgview.hidden=NO;
    
    lab2.text=[NSString stringWithFormat:@"%@%@",dealFlag,[dict objectForKey:@"senddt"]];
    
    lab13.text=[self removeHTML:[dict objectForKey:@"shortMsg"]];
    
    if (isegment==0)
        lab14.text=[dict objectForKey:@"sendemp"];
    else
      lab14.text=[dict objectForKey:@"objdpm"];
    
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (isegment==0) {
        if (iRtnCount==1 && indexPath.row==arrList.count)
            return;
        OAReceiveDetailViewController* vc=[[OAReceiveDetailViewController alloc] init];
        vc.arrList=arrList;
        vc.iindex=(int)indexPath.row;
        [self presentViewController:vc animated:NO completion:nil];
//        UINavigationController *navRegist = [[UINavigationController alloc] initWithRootViewController:vc];
//        [self.navigationController presentViewController:navRegist animated:NO completion:nil];
    } else if (isegment==1) {
        OASendDetailViewController* vc=[[OASendDetailViewController alloc] init];
        vc.arrList=arrList;
        vc.iindex=(int)indexPath.row;
        [self presentViewController:vc animated:NO completion:nil];
    } else if (isegment==2) {
        OANewEmailViewController* vc=[[OANewEmailViewController alloc] init];
        OATempMail* tempMail=[arrList objectAtIndex:indexPath.row];
        vc.openTempMail=tempMail;
        [self presentViewController:vc animated:NO completion:nil];
    }
}
- (NSString *)removeHTML:(NSString *)html {
    NSScanner *theScanner;
    NSString *text = nil;
    
    theScanner = [NSScanner scannerWithString:html];
    
    while ([theScanner isAtEnd] == NO) {
        // find start of tag
        [theScanner scanUpToString:@"<" intoString:NULL] ;
        // find end of tag
        [theScanner scanUpToString:@">" intoString:&text] ;
        // replace the found tag with a space
        //(you can filter multi-spaces out later if you wish)
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>", text] withString:@" "];
    }
    
    return html;
}
/*
 {
 billcode = "                              ";
 dealFlag = 0;
 hasAttach = 0;
 msgid = 54;
 objdpm = "abc,\U8d85\U7ea7\U7528\U6237,abc1";
 readflag = 1;
 senddt = "2014-12-08 15:37:23";
 sendemp = abc;
 shortMsg = test;
 title = test;
 type = 0;
 }
 
 msgid	int	是		邮件ID
 title	string	是		邮件标题
 shortMsg	string	是		简短邮件内容（长度15个字符，过滤html）
 sendemp	string	是		发送人
 objdpm	string	是		接收人
 billcode	string	是		相关单号
 has Attach	int	是		附件数量
 senddt	string	是		发送日期
 type	int	是		0-收件 1-发件
 read_flag	int	是		是否已读,只限收件
 dealflag	int	是		是否确认,只限收件
 dealdt	string	是		确认时间,只限收件
 */
//        UIFont *font = [UIFont systemFontOfSize:10];
//        NSString* tt=[dict objectForKey:@"content"];
//        NSDictionary *tdic = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil];
//        CGSize s = [tt boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-35.0-10.0*3,MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:tdic context:nil].size;
//        lab13.width=s.width;
@end
